package com.cskaoyan.config;

import com.cskaoyan.model.realm.UsernamePasswordTypeToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author:
 * @description:
 * @keypoint:
 * @tags:
 * @related:
 */

public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {

    /**
     * 重写这个方法，完成realm的分发
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> originRealm = this.getRealms();

        UsernamePasswordTypeToken token = (UsernamePasswordTypeToken) authenticationToken;
        String type = token.getType();

        List<Realm> realms = new ArrayList<>();
        for (Realm realm : originRealm) {
            if(realm.getName().toLowerCase().contains(type)){
                realms.add(realm);
            }
        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);

    }
}
